/*
 * Copyright@www.it1997.com.
 * @Author: 陈晓晨
 * @Date: 2020/6/8
 * Description:版权所有 QQ:376231445
 */

package com.it1997.it1997admin.handler;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.it1997.it1997admin.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@Log4j2
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

    private MyAuthenticationProvide authenticationProvide;
    public JWTLoginFilter(MyAuthenticationProvide authenticationManager) {
        this.authenticationProvide=authenticationManager;
    }

    /*
    * 自定义登录验证
    * */
    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
                User user=new ObjectMapper().readValue(request.getInputStream(),User.class);
                log.info(user.getCaptcha());
            return authenticationProvide.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(),
                            user.getPassword(),
                            new ArrayList<>()));
            }catch (IOException e){
            throw  new RuntimeException(e);
        }
    }
/*
* 验证登录成功后执行
* */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            as.append(authority.getAuthority())
                    .append(",");
        }
        Map<String, Object> claims=new HashMap<String, Object>();
        claims.put("authorities",as);
        claims.put("username",((User)authResult.getPrincipal()).getUsername());
        String token= Jwts.builder()
                //.setSubject(((User)authResult.getPrincipal()).getUsername())
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 10*60*1000))
                .signWith(SignatureAlgorithm.HS512, "MyJwtSecret")
                .compact();
            response.addHeader("Authorization","Bearer "+token);
    }
}
